#!/bin/bash

# 1.初始化示例目录:
# mkdir -p examples && touch examples/.gitkeep

# 2.添加到 CMakeLists.txt
# # 示例集合
# option(ENABLE_BUILD_EXAMPLES "Enable Build Examples." OFF)
# if(ENABLE_BUILD_EXAMPLES)
#     include(examples/dev.cmake)
# endif(ENABLE_BUILD_EXAMPLES)
# 
# # 测试集合
# option(ENABLE_BUILD_TESTS "Enable Build Tests." OFF)
# if(ENABLE_BUILD_TESTS)
#     add_subdirectory(tests)
# endif(ENABLE_BUILD_TESTS) 
#

set -e

# 0. 进入当前脚本所在目录
script_dir=$(cd "$(dirname "$0")" && pwd)
cd "$script_dir" || exit 1

# 1. 检查命令行参数
name=${1}
if [ -z "$name" ]; then
    echo "Usage:  <example name>"
    exit 1
fi

# 2. 扫描用例目录
exampledir=
if [ -d "example" ]; then
    echo "directory \"example\" exists"
    exampledir=example
elif [ -d "examples" ]; then
    echo "directory \"examples\" exists"
    exampledir=examples
elif [ -d "src/examples" ]; then
    echo "directory \"src/examples\" exists"
    exampledir=src/examples
else
    echo "directory \"test\" or \"tests\" does not exist"
    exit 1
fi

# 3. 检查测试目录是否存在
folder="$exampledir/$name"

echo "Generating test $folder..."
if [[ -d "$folder" && -f "$folder/$name.cpp" ]]; then
    echo "directory \"$folder\" exists"
    echo "directory \"$folder/main.cpp\" exists"
    exit 0
fi

# 4. 创建测试目录
mkdir -p "$folder"

# 5. 创建测试文件 Console
echo "Creating console example..."
    cat > "$folder/$name.cpp" << EOF
#include <iostream>

int	main(int argc, char **argv)
{
    std::cout << "Hello World" << std::endl;

    return 0;
}
EOF
    # 将测试添加到 dev.cmake
    cat >> "$exampledir/dev.cmake" << EOF
# find $exampledir/$name | grep -E '.h$|.cpp$' | sort
add_executable(example-$name
    $exampledir/$name/$name.cpp
)

EOF

echo "Generated example $folder"
